<template>
  <ElRow>
    <ElCol :span="24"
      ><span class="must-check no-content">* </span>项目图片：
      <div class="img-container">
        <div class="product-image">
          <img v-if="imgUrl" :src="imgUrl" width="100%" />
          <img v-else-if="img" :src="img" width="100%" />
        </div>
        <ElUpload
          ref="uploadImg"
          class="avatar-uploader"
          :action="url.uploadImg"
          :headers="headers"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :on-progress="handleProgress"
          :name="'photo'"
          :data="{thumb: -750}"
          :list-type="'picture'"
          :show-file-list="false"
        >
          <ElButton type="primary" round :loading="imgLoading"
            >点击上传</ElButton
          >
        </ElUpload>

        <ElButton type="primary" round @click="handleRemove">删除</ElButton>
      </div>
    </ElCol>
  </ElRow>
</template>

<script>
import Cookie from 'js-cookie';
import {catchAppError} from '@/util';
import url from '@/config';

export default {
  props: {
    img: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      url,
      headers: {
        token: Cookie.get('token')
      },
      imgUrl: '',
      thumbnail: '',
      imgLoading: false
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imgLoading = false;
      this.$emit('imgLoading', this.imgLoading);
      this.imgUrl = URL.createObjectURL(file.raw);
      this.thumbnail = res.data.path;
      this.$emit('photoImgUrl', this.thumbnail);
    },
    handleAvatarError(err) {
      this.imgLoading = false;
      catchAppError(err);
    },
    handleRemove() {
      this.thumbnail = '';
      this.imgUrl = '';
    },
    handleProgress() {
      this.imgLoading = true;
      this.$emit('imgLoading', this.imgLoading);
    }
  }
};
</script>

<style lang="scss">
.img-container {
  display: inline-block;
  vertical-align: top;
  .product-image {
    width: 110px;
    height: 110px;
    border: 1px dashed #666;
    display: inline-block;
    margin-right: 25px;
    vertical-align: bottom;
  }
  .avatar-uploader,
  .el-button {
    display: inline-block;
    margin-right: 25px;
    vertical-align: bottom;
  }
}
</style>
